<template>
  <div class="rec" style="width:80%; margin: auto;">
    <div class="customer-service">
      <h3>在线客服</h3>
      <textarea v-model="userInput" placeholder="请输入您的问题..."></textarea>
      <button @click="sendMessage">发送</button>
      <div v-for="(message, index) in chatLog" :key="index" class="chat-message">
        <span v-if="message.from === 'user'">{{ message.content }}</span>
        <span v-else>{{ message.content }}</span>
      </div>
    </div>
    <div style="display: flex">
      <el-row style="margin-top: 30px;flex: 1;">
        <!--      图片绑定-->
        <!--      <el-col v-for="(path, index) in imagePaths" :key="index" :span="6">
                <img :src="path" alt="Image" class="grid-content bg-purple">
              </el-col>-->
        <!--      默认图片-->
        <el-col>
          <img :src="defaultImg" alt="Image" class="itemImg bg-purple">
        </el-col>
      </el-row>
      <el-row style="margin-top: 30px;flex: 2;text-align: left;">
        <el-col>
          <div class="item-info">
            <h2>{{ item.name }}</h2>
            <!--            <p>库存：{{ item.stock }}</p>-->
            <!--          <p>图片路径：{{ item.imgUrl }}</p>-->
            <p style="margin-top:100px">商品描述：{{ item.describe }}</p>
            <p style="margin-top: 40px">尺寸：{{ item.size }}</p>
            <p style="margin-top: 40px">{{ item.price }} 元</p>

          </div>
        </el-col>
        <el-col :span="24">
          <div class="item-info" style="">
            <el-button style="width: 30%" type="primary" @click="buy">立即购买</el-button>
            <el-button style="margin-left: 20px;width: 30%" type="primary" @click="addToCart(item)">添加购物车
            </el-button>
          </div>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "ItemDetail",
  data() {
    return {
      imagePaths: [
        require('@/assets/items/1.png'),
        require('@/assets/items/2.png'),
        require('@/assets/items/3.png'),
        require('@/assets/items/4.png'),
      ],
      defaultImg: require('@/assets/items/4.png'),
      itemId: null,
      item: {}, // 用于存储获取到的商品详情数据
      userInput: '',
      chatLog: []
    };
  },
  mounted() {
    this.itemId = this.$route.params.id; // 获取路由参数中的商品ID
    this.fetchItemDetails();
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') {
        alert('请输入问题！');
        return;
      }

      try {
        const response = await axios.post('/ai/aliTyqw', { // 替换为你的后端接口路径
          userInput: this.userInput
        });

        // 假设后端返回的数据结构为{ botResponse: 'AI的回复内容' }
        const botResponse = response.data.botResponse;

        // 将用户输入和AI回复添加到聊天日志中
        this.chatLog.push({from: 'user', content: this.userInput});
        this.chatLog.push({from: 'bot', content: botResponse});

        // 清空输入框
        this.userInput = '';

        // // 强制刷新组件
        // this.$forceUpdate();
      } catch (error) {
        console.error('发送消息失败：', error);
        alert('发送消息失败，请稍后再试！');
      }
    },
    fetchItemDetails() {
      axios.get(`/item/find/${this.itemId}`).then(response => {
        if (response.data && response.data.data) {
          this.item = response.data.data; // 确保 response.data 不是 null 并且包含 data 属性
          this.imagePaths = this.item.imagePaths; // 假设返回的数据中包含了图片路径数组
        } else {
          console.error("Error parsing item details:", response.data);
        }
      }).catch(error => {
        console.error("Error fetching item details:", error);
      });
    },
    addToCart(item) {
      axios.post('/cart/add', {
        itemId: item.id,
        amount: 1, // 初始添加数量为1
        price: item.price // 假设价格已经包含在 item 对象中
      }).then(response => {
        // 假设后端返回的数据中包含一个表示操作成功的状态码或消息
        if (response.data.success || response.status === 200) { // 根据你的后端API实际情况调整
          this.$message({
            message: '添加成功！',
            type: 'success' // 可以是 'success', 'warning', 'info', 'error'
          });
          // 如果需要，可以触发一个自定义事件来更新购物车总数
          this.$emit('cart-updated', response.data);
        } else {
          // 如果后端返回了错误，你也可以在这里处理
          this.$message.error('添加失败！');
        }
      }).catch(error => {
        console.error('Error adding item to cart:', error);
        // 在catch块中，你也可以显示一个错误消息
        this.$message.error('网络错误，请稍后再试！');
      });
    },
  },


}
</script>

<style scoped>
.rec {
  text-align: center; /* 设置文本居中 */
  width: 60%;
  margin: auto;
}

.itemImg {
  width: 300px;
  height: 400px;
}

.title {
  margin: 10px auto;
  width: 25%;
  border-radius: 5px;
  padding: 10px 0;
  height: auto;
  font-size: 20px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 0 4px rgba(0, 0, 0, 0.04);
}

.item-info {
  padding: 14px;
  margin-left: 20px;
}

.item-info button {
  width: 100px;
  background: linear-gradient(to right bottom, #e33112, #ffb199);
  border: none;
  font-weight: bold;

}

.item-info button:hover {
  background: linear-gradient(to right bottom, #ff7676, #ffb199);
//opacity: 0.6; font-weight: bold;
}

.sizes {
  list-style: none;
  padding: 0;
  margin: 0;
}

.sizes li {
  display: inline-block;
  padding: 5px 10px;
  border: 1px solid #ccc;
  cursor: pointer;
}

.sizes li:hover {
  background-color: #f0f0f0;
}

.chat-message {
  margin-top: 20px;
  padding: 10px;
  background-color: #e9e9e9;
  border-radius: 4px;
}

.chat-message span {
  display: block;
  word-wrap: break-word; /* 允许长单词换行 */
}

.chat-message span:nth-child(odd) {
  background-color: #d9edf7;
  border-radius: 4px;
  padding: 5px;
  margin-bottom: 5px;
}

.chat-message span:nth-child(even) {
  background-color: #dff0d8;
  border-radius: 4px;
  padding: 5px;
  margin-bottom: 5px;
  text-align: right;
}
</style>
